﻿using Blm.Utils.Extensions;
using Language.Resource;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Swashbuckle.AspNetCore.Annotations;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Ms;
using VisionCloud.Domain.Extension;
using VisionCloud.Domain.Filters;
using VisionCloud.Service.Ms;
using static VisionCloud.Core.Model.Sys.SysUser;
using OperationException = VisionCloud.Domain.Common.OperationException;

namespace VisionCloud.Api.Controllers.Ms
{
    /// <summary>
    /// 报表数据模块
    /// </summary>
    [SystemModule("报表数据")]
    [ApiAuthorize(PolicyEnum.RequireRolePermission)]
    [ApiVersion("1.0")]
    [Route("api/ms/[controller]/[Action]")]
    [ApiExplorerSettings(GroupName = "报表数据")]
    public partial class StatisController : ApiBaseController
    {
        /// <summary>
        /// 报告数据统计服务
        /// </summary>
        public StatisService StatisService { get; set; }

        /// <summary>
        /// 任务报告服务
        /// </summary>
        public MsReportService MsReportService { get; set; }

        /// <summary>
        /// 工效分析服务
        /// </summary>
        public EfficiencyAnalyzeService EfficiencyAnalyzeService { get; set; }

        /// <summary>
        /// 质量分析服务
        /// </summary>
        public QualityAnalyzeService QualityAnalyzeService { get; set; }

        /// <summary>
        /// 进度分析服务
        /// </summary>
        public ProgressAnalyzeService ProgressAnalyzeService { get; set; }

        /// <summary>
        /// ProjectService
        /// </summary>
        public ProjectService ProjectService { get; set; }

        /// <summary>
        /// 多语言资源
        /// </summary>
        public IStringLocalizer<CommonResource> CommonLocalizer { get; set; }

        /// <summary>
        /// 多语言资源
        /// </summary>
        public IStringLocalizer<ControllerResource> ControllerLocalizer { get; set; }

        #region 客户API

        /// <summary>
        /// 作者：黄钧航
        /// 分页-获取项目信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetList(MsProjectListCondition model)
        {
            return await TryCatchAsync(ProjectService.GetList(model));
        }

        /// <summary>
        /// 作者：黄钧航
        /// 获取当前项目的综合、测量项和楼栋合格率
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetProjectQualityData(MsCondition condition)
        {
            return await TryCatchAsync(Task.Run(async () =>
            {
                return await QualityAnalyzeService.GetProjectQualityData(condition);
            }));
        }

        /// <summary>
        /// 作者：黄钧航
        /// 分页获取当前项目的综合、测量项和楼栋合格率
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetProjectQualityPageData(MsProjectPageCondition condition)
        {
            return await TryCatchAsync(Task.Run(async () =>
            {
                return await QualityAnalyzeService.GetProjectQualityPageData(condition);
            }));
        }

        /// <summary>
        /// 根据项目Id、楼栋号和楼层信息获取点云和户型图数据
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "测量服务" })]
        public async Task<ApiResult> GetPointCloudData(MsCondition condition)
        {
            return await TryCatchAsync(Task.Run(async () =>
            {
                return await StatisService.GetPointCloudData(condition);
            }));
        }

        /// <summary>
        /// 上次实测点云经过算法计算后生成图片资源文件
        /// </summary>
        /// <param name="formCollection"></param>
        /// <param name="path">路径</param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "测量服务" })]
        public async Task<ApiResult> UploadMeasuringSourceData(IFormCollection formCollection)
        {
            if (formCollection.Files?.Count > 0)
            {
                return await TryCatchAsync(StatisService.UploadMeasuringSourceData(formCollection));
            }
            return new ApiResult(Domain.Common.AjaxCode.Error, ControllerLocalizer["FileCannotEmpty"]);
        }

        #endregion 客户API

        /// <summary>
        /// 作者：黄钧航
        /// 获取每个项目的综合合格率
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "质量分析" })]
        public async Task<ApiResult> GetProjectListNew(MsCondition condition)
        {
            return await TryCatchAsync(QualityAnalyzeService.GetProjectListNew(condition));
        }

        /// <summary>
        /// 数据分析-质量分析-分页获取报告整体合格率
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "质量分析" })]
        [SwaggerResponse(0, "获取列表数据的字段：PageData", typeof(ProjectOverallPassRatePara))]
        public async Task<ApiResult> GetProjectOverallPassRatePage(ProjectOverallPassRatePara condition)
        {
            return await TryCatchAsync(QualityAnalyzeService.GetProjectOverallPassRatePage(condition));
        }

        /// <summary>
        /// 作者：黄钧航
        /// 下载质量分析数据
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "质量分析" })]
        [SwaggerResponse(0, "下载质量数据：PageData", typeof(MsCondition))]
        public async Task<ApiResult> QualityDataToExcelFile(MsCondition condition)
        {
            return await TryCatchAsync(Task.Run(async () =>
            {
                CheckProjectId(condition);
                return await TryCatchAsync(QualityAnalyzeService.QualityDataToExcelFile(condition));
            }));
        }

        /// <summary>
        /// 检查项目Id
        /// </summary>
        /// <param name="condition"></param>
        private void CheckProjectId(MsCondition condition)
        {
            if (string.IsNullOrWhiteSpace(condition.ProjectId) || condition.ProjectId == Guid.Empty.ToString())
            {
                throw new OperationException(ControllerLocalizer["YB0008"].Value);
            }
            if (!condition.ProjectId.IsGuid())
            {
                throw new OperationException(ControllerLocalizer["YB0014"].Value);
            }
        }

        /// <summary>
        /// 作者：黄钧航
        /// 获取当前项目的综合、测量项和楼栋合格率
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "质量分析" })]
        [SwaggerResponse(0, "获取列表数据的字段：Result", typeof(MsCondition))]
        public async Task<ApiResult> GetSQualityAnalysisData(MsCondition condition)
        {
            return await TryCatchAsync(Task.Run(async () =>
            {
                CheckProjectId(condition);
                return await QualityAnalyzeService.GetSQualityAnalysisData(condition);
            }));
        }

        /// <summary>
        /// 作者：黄钧航
        /// 获取当前楼栋的楼层，分户和站点测量数据
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "质量分析" })]
        [SwaggerResponse(0, "获取列表数据的字段：Result", typeof(MsCondition))]
        public async Task<ApiResult> GetSQualityAnalysisBuildingData(MsCondition condition)
        {
            return await TryCatchAsync(Task.Run(async () =>
            {
                CheckProjectId(condition);
                if (string.IsNullOrWhiteSpace(condition.Build))
                {
                    throw new OperationException(ControllerLocalizer["YB0015"].Value);
                }

                return await QualityAnalyzeService.GetSQualityAnalysisBuildingData(condition);
            }));
        }

        /// <summary>
        /// 作者：黄钧航
        /// 获取所有用户的测量进度
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [Obsolete("由于逻辑调整，此接口已弃用，请使用分页接口GetUserProgressList")]
        [HttpPost, SwaggerOperation(Tags = new[] { "工效分析" })]
        public async Task<ApiResult> GetUserProgress(MsUserDto user)
        {
            return await TryCatchAsync(EfficiencyAnalyzeService.GetUserProgress(user));
        }

        /// <summary>
        /// 作者：黄钧航
        /// 获取当前用户的测量进度
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [Obsolete("由于逻辑调整，此接口已弃用，请使用接口GetUserEfficiencyDetail")]
        [HttpPost, SwaggerOperation(Tags = new[] { "工效分析" })]
        public async Task<ApiResult> GetMsSPersonnelEfficiencyData(MsUserDto user)
        {
            return await TryCatchAsync(Task.Run(async () =>
            {
                CheckUserId(user);
                return await TryCatchAsync(EfficiencyAnalyzeService.GetMsSPersonnelEfficiencyData(user));
            }));
        }

        /// <summary>
        /// 获取用户的测量进度列表
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "工效分析" })]
        [SwaggerResponse(0, "获取列表数据的字段：Result", typeof(AreaFloorResponseDto))]
        public async Task<ApiResult> GetUserEfficiencyList([FromBody] AreaFloorRequestDto condition)
        {
            return await TryCatchAsync(EfficiencyAnalyzeService.GetUserProgressPage(condition));
        }

        /// <summary>
        /// 获取某个用户的测量进度详情
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "工效分析" })]
        [SwaggerResponse(0, "获取详情数据的字段：Result", typeof(EfficiencyDetailResponseDto))]
        public async Task<ApiResult> GetUserEfficiencyDetail(EfficiencyDetailRequestDto condition)
        {
            return await TryCatchAsync(EfficiencyAnalyzeService.GetUserEfficiencyDetail(condition));
        }

        /// <summary>
        /// 获取项目测量进度列表
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "工效分析" })]
        [SwaggerResponse(0, "获取列表数据的字段：Result", typeof(AreaFloorResponseDto))]
        public async Task<ApiResult> GetProjectEfficiencyList(AreaFloorRequestDto condition)
        {
            return await TryCatchAsync(EfficiencyAnalyzeService.GetProjectProgressPage(condition));
        }

        /// <summary>
        /// 获取某个项目的测量进度详情
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "工效分析" })]
        [SwaggerResponse(0, "获取详情数据的字段：Result", typeof(EfficiencyDetailResponseDto))]
        public async Task<ApiResult> GetProjectEfficiencyDetail(EfficiencyDetailRequestDto condition)
        {
            return await TryCatchAsync(EfficiencyAnalyzeService.GetProjectEfficiencyDetail(condition));
        }

        /// <summary>
        /// 获取设备测量进度列表
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "工效分析" })]
        [SwaggerResponse(0, "获取列表数据的字段：Result", typeof(AreaFloorResponseDto))]
        public async Task<ApiResult> GetDeviceEfficiencyList(AreaFloorRequestDto condition)
        {
            return await TryCatchAsync(EfficiencyAnalyzeService.GetDeviceProgressPage(condition));
        }

        /// <summary>
        /// 获取某个设备工作的测量进度详情
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "工效分析" })]
        [SwaggerResponse(0, "获取详情数据的字段：Result", typeof(EfficiencyDetailResponseDto))]
        public async Task<ApiResult> GetDeviceEfficiencyDetail(EfficiencyDetailRequestDto condition)
        {
            return await TryCatchAsync(EfficiencyAnalyzeService.GetDeviceEfficiencyDetail(condition));
        }

        /// <summary>
        /// 检查用户Id
        /// </summary>
        /// <param name="user"></param>
        private void CheckUserId(MsUserDto user)
        {
            if (string.IsNullOrEmpty(user.Id))
            {
                throw new OperationException(ControllerLocalizer["YB0016"].Value);
            }
            if (!user.Id.IsGuid())
            {
                throw new OperationException(ControllerLocalizer["YB0017"].Value);
            }
        }

        /// <summary>
        /// 作者：黄钧航
        /// 工效分析--下载数据
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "工效分析" })]
        public async Task<ApiResult> EfficiencyDataToExcelFile(MsUserDto user)
        {
            return await TryCatchAsync(Task.Run(async () =>
            {
                CheckUserId(user);
                return await EfficiencyAnalyzeService.EfficiencyDataToExcelFile(user);
            }));
        }

        /// <summary>
        /// 作者：黄钧航
        /// 获取总工效数据
        /// </summary>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "工效分析" })]
        [SwaggerResponse(0, "获取详情数据的字段：Result", typeof(SummayWorkEfficiency))]
        public async Task<ApiResult> GetEfficiencySummaryData(TimeConditon conditon)
        {
            return await TryCatchAsync(Task.Run(async () =>
            {
                CheckDateTime(conditon);
                return await EfficiencyAnalyzeService.GetEfficiencySummaryData(conditon);
            }));
        }

        /// <summary>
        /// 检查时间格式
        /// </summary>
        /// <param name="conditon"></param>
        private void CheckDateTime(TimeConditon conditon)
        {
            if (string.IsNullOrWhiteSpace(conditon.StartTime))
            {
                conditon.StartTime = DateTime.MinValue.ToString("yyyy-MM-dd");
            }
            if (!DateTime.TryParse(conditon.StartTime, out _))
            {
                throw new OperationException(ControllerLocalizer["YB0018"].Value);
            }
            if (string.IsNullOrWhiteSpace(conditon.EndTime))
            {
                throw new OperationException(ControllerLocalizer["YB0020"].Value);
            }
            if (!DateTime.TryParse(conditon.EndTime, out _))
            {
                throw new OperationException(ControllerLocalizer["YB0019"].Value);
            }
        }

        /// <summary>
        /// 作者：黄钧航
        /// 下载总工效数据
        /// </summary>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "工效分析" })]
        public async Task<ApiResult> DownloadEfficiencySummaryData(TimeConditon conditon)
        {
            return await TryCatchAsync(Task.Run(async () =>
            {
                CheckDateTime(conditon);

                return await TryCatchAsync(EfficiencyAnalyzeService.DownloadEfficiencySummaryData(conditon));
            }));
        }

        /// <summary>
        /// 获取项目报告统计数据
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "工效分析" })]
        public async Task<ApiResult> GetStatisticsData(ReportStatisDto condition)
        {
            return await TryCatchAsync(StatisService.GetProjectStatis(condition));
        }

        /// <summary>
        /// 分页获取各个项目进度信息
        /// </summary>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "进度分析" })]
        public async Task<ApiResult> GetProjectProgressPageInfo(MsProjectCondition msProjectCondition)
        {
            return await TryCatchAsync(ProgressAnalyzeService.GetProjectProgressPageInfo(msProjectCondition));
        }

        /// <summary>
        /// 进度分析单个项目详情页面接口
        /// </summary>
        /// <param name="requestDto"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "进度分析" })]
        public async Task<ApiResult> GetProjectProgressDetail(ProjectProgressDetailRequestDto requestDto)
        {
            return await TryCatchAsync(ProgressAnalyzeService.GetProjectProgressDetail(requestDto));
        }

        /// <summary>
        /// 导出项目进度信息
        /// </summary>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "进度分析" })]
        public async Task<ApiResult> ExportProgressToExcelFile(MsProjectCondition msProjectCondition)
        {
            return await TryCatchAsync(ProgressAnalyzeService.ExportProgressToExcelFile(msProjectCondition));
        }

        /// <summary>
        /// 获取项目进度信息
        /// </summary>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "进度分析" })]
        public async Task<ApiResult> GetProjectProgress(MsProjectCondition msProjectCondition)
        {
            return await TryCatchAsync(ProgressAnalyzeService.GetProjectProgress(msProjectCondition));
        }

        /// <summary>
        /// 获取楼栋楼层的报告
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "数据报告" })]
        [SwaggerResponse(0, "获取楼栋楼层的报告", typeof(string))]
        public async Task<ApiResult> GetSummaryReport(GetSummaryReportRqDto request)
        {
            var result = await MsReportService.GetSummaryReportPath(request);
            return new ApiResult
            {
                Code = AjaxCode.Success,
                Message = ControllerLocalizer["YB0021"].Value,
                Result = result
            };
        }

        /// <summary>
        /// 获取项目报告列表
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "数据报告" })]
        public async Task<ApiResult> GetReportList(ReportSearchDto condition)
        {
            condition.UserId = TokenModel.YunUserGuid;
            condition.UserType = (EnumUserType)TokenModel.UserType;
            return await TryCatchAsync(MsReportService.GetReportList(condition));
        }

        /// <summary>
        /// 获取最新消息方法，
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetNewMessage()
        {
            return await TryCatchAsync(StatisService.GetNewMessage());
        }

        /// <summary>
        /// 设置任务的报告为已读状态
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "数据报告" })]
        public async Task<ApiResult> UserIsReadedTask(UserIsReadedTaskDto condition)
        {
            return await TryCatchAsync(StatisService.UserIsReadedTask(condition)).ConfigureAwait(false);
        }

        /// <summary>
        /// 批量删除报表
        /// </summary>
        /// <param name="listTaskId"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "数据报告" })]
        [ApiAuthorize(PolicyEnum.RequireAdmin)]
        public async Task<ApiResult> BatchDeleteReport(List<Guid> listTaskId)
        {
            return await TryCatchAsync(MsReportService.BatchDeleteReport(listTaskId));
        }

        /// <summary>
        /// 作者：黄钧航
        /// 下载文件
        /// </summary>
        /// <param name="listTaskId"></param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "数据报告" })]
        [ApiAuthorize(PolicyEnum.RequireAdmin)]
        public async Task<ApiResult> DownloadReport(List<Guid> listTaskId)
        {
            await Contracts.Frequency($"user_downreport_limit_{TokenModel.Id}", 1, TimeSpan.FromSeconds(3), CommonLocalizer["YB0449"].Value);
            return await TryCatchAsync(MsReportService.DownloadReport(listTaskId));
        }

        /// <summary>
        /// 作者：黄钧航
        /// 分享报告文件
        /// </summary>
        /// <param name="dto">任务对象</param>
        /// <returns></returns>
        [HttpPost, SwaggerOperation(Tags = new[] { "数据报告" })]
        public async Task<ApiResult> SharingReport(MsTaskDto dto)
        {
            return await TryCatchAsync(MsReportService.SharingReport(dto));
        }
    }
}